#include "privatechat.h"
#include "ui_privatechat.h"
#include "protool.h"//协议
#include "tcpclient.h"//获得我方的名字 也就是loginname2eg
#include <QMessageBox>

privateChat::privateChat(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::privateChat)
{
    ui->setupUi(this);
}

privateChat::~privateChat()
{
    delete ui;
}

void privateChat::setChatName(QString strName)
{
    m_strChatName = strName;//将传过来的名字保存在成员变量中
    m_strLoginName = TcpClient::getInstance().loginName();

}

void privateChat::updateMsg(const PDU *pdu)
{
    if(pdu == nullptr) return;
    char caSendName[32] = {'\0'};
    memcpy(caSendName,pdu->caData,32);
    QString strMsg = QString("%1 says : %2").arg(caSendName).arg((char*)pdu->caMsg);//int to char*
    ui->showMsg_te->append(strMsg);//在textedit上显示信息



}

privateChat &privateChat::getInstance()//单例调用
{
    static privateChat instance;
    return instance;//单例模式
}


void privateChat::on_sendMsg_pb_clicked()//发送信息的信号槽
{
    QString strMsg = ui->inputMsg_le->text();//获取其中的内容
    if(!strMsg.isEmpty())
    {
        PDU *pdu = mkPDU(strMsg.size()+1);//名字放在cadata，所以消息需要单独申请空间，空间长度就是字符串大小
        pdu->uiMsgType = ENUM_MSG_TYPE_PRIVATE_CHAT_FRIEND_REQUEST;
        memcpy(pdu->caData,m_strLoginName.toStdString().c_str(),m_strLoginName.size());//自己的姓名,c_str返回当前字符串的首字符地址
        memcpy(pdu->caData+32,m_strChatName.toStdString().c_str(),m_strChatName.size());
        strcpy((char*)pdu->caMsg,strMsg.toStdString().c_str());


        TcpClient::getInstance().getTcpSocket().write((char*)pdu,pdu->uiPDULen);//将pdu发送给服务器
        free(pdu);
        pdu = nullptr;

    }
    else
    {
        QMessageBox::warning(this,"私聊","发送的聊天信息不能为空");
    }

}
